import { createRouter, createWebHashHistory,RouterView } from 'vue-router'
// import store from "@/store/index"
import LayOut from '@/views/LayOut'
import home from '@/views/home'
import Topcategory from '@/views/category/index.vue'
import Subcategory from '@/views/category/sub.vue'
import GoodsRelevant from '@/views/goods'
import Login from '@/views/login'
import LoginCallback from '@/views/login/callback'
import XtxCartPage from "@/views/cart"
import store from '@/store'
import Checkout from "@/views/member/play/checkout.vue"
import Pay from "@/views/member/play"
import payResult from "@/views/member/play/result.vue"
import memLayout from "@/views/member/layout.vue"
import memHome from "@/views/member/home"
import MemberOrder from "@/views/member/order"
import MemberDetailed from"@/views/member/order/detailed.vue"
import {h} from "vue"
// 路由规则
const routes = [
  {
    path: '/',
    component: LayOut,
    children: [{
      path: '',
      component: home,
      name: 'home'
    }, {
      // 分类列表
      path: '/topcategory/:id',
      component: Topcategory
    }, {
      // 分类列表的二级路由
      path: '/topcategory/sub/:id',
      component: Subcategory
    }, {
      // 分类列表的二级路由
      path: '/product/:id',
      component: GoodsRelevant
    },{
      path:'/product/cart',
      component:XtxCartPage
    },{
      path:'/member/checkout',
      component:Checkout
    },{
      path:'/member/pay',
      component:Pay
    },{
      path:'/pay/callback',
      component:payResult
    },{
      path:'/member',
      component:memLayout,
      children:[{
        path:'/member',
        component:memHome,
        name:'memHome'
      },{
        path:'/member/order',
        component:{render:()=>h(<RouterView/>)},
        children:[{
          path:'',
          component:MemberOrder,
        },{
          path:':id',
          component:MemberDetailed,
        }]
      }]
    }]

  }, {
    path: '/login',
    component: Login
  },
  {
    path: '/login/callback',
    component: LoginCallback
  }
]
// 创建路由
// vue2.0new VueRouter({})
// vue3.0 createRouter({})
const router = createRouter({
  // 使用哈希路由
  history: createWebHashHistory(),
  routes,
  // 路由跳转页面滚动到顶部
  scrollBehavior () {
    return { top: 0 }
  }
})
//路由前置导航
router.beforeEach((to,from,next)=>{
  console.log(to);
  const {profile}=store.state.user

  //路由地址以/member开头的全部拦截需要登录
  if(!profile.token && to.path.startsWith('/member') ){
    //encodeURIComponent将有特殊字符串的进行编码
    return next('/login?redirectUrl='+encodeURIComponent(to.fullPath))
  }
  next()
})
export default router
